package bizlogic;

import java.util.ArrayList;

import model.UserDTO;
import model.search.UserSearchDTO;
import dao.DAOException;
import dao.DAOFactory;
import dao.UserDAO;

public class UserManager {
	private UserDAO userDAO = null;

	public UserManager() {
		userDAO = DAOFactory.loadInstance().getUserDAO();
	}
	
	public ArrayList<UserDTO> getAll() {
		ArrayList<UserDTO> list = new ArrayList<UserDTO>();
		
		try {
			list = userDAO.getAll();
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	public ArrayList<UserDTO> getManagers() {
		ArrayList<UserDTO> list = new ArrayList<UserDTO>();
		
		UserSearchDTO us = new UserSearchDTO();
		us.setType("Manager");
		us.setStatus(1);
		
		try {
			list = userDAO.findUserByCriteria(us);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	public UserDTO getUser(String id) {
		UserDTO data = null;
		
		try {
			data = userDAO.getUser(id);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		return data;
	}
	
	public UserDTO doLogin(String username, String password) {
		UserDTO user = null;
		ArrayList<UserDTO> users = null;
		UserSearchDTO searchCriteria = new UserSearchDTO();
		
		searchCriteria.setId(username);
		searchCriteria.setPassword(password);
		searchCriteria.setStatus(1);
		
		try {
			users = userDAO.findUserByCriteria(searchCriteria);
			
			if ( users.size() > 0 ) user = users.get(0);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		return user;
	}
	
	public ArrayList<UserDTO> findUserByCriteria(UserSearchDTO src) {
		ArrayList<UserDTO> list = new ArrayList<UserDTO>();
		
		try {
			list = userDAO.findUserByCriteria(src);
		} catch (DAOException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	public String insertUser(UserDTO data) {
		String error = "";
		
		try {
			userDAO.insertUser(data);
		} catch (DAOException e) {
			error = "user.error.oninsert";
			e.printStackTrace();
		}
		
		return error;
	}
	
	public String updateUser(UserDTO data) {
		String error = "";
		
		try {
			userDAO.updateUser(data);
		} catch (DAOException e) {
			error = "user.error.onupdate";
			e.printStackTrace();
		}
		
		return error;
	}
	
	public String deleteUser(UserDTO data) {
		String error = "";
		
		try {
			userDAO.deleteUser(data);
		} catch (DAOException e) {
			error = "user.error.ondelete";
			e.printStackTrace();
		}
		
		return error;
	}
	
}
